package de.sendorian.app.forumArchive.domain;

import static org.apache.commons.lang.StringUtils.startsWith;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Transient;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import de.sendorian.app.forumArchive.Config;


@Configurable
@Entity
public class Forum {

    @Id
    @GeneratedValue
    private int id;

    private String name;

    private String url;

    @OneToMany(cascade = CascadeType.ALL)
    @Cascade(value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    @Fetch(FetchMode.SUBSELECT)
    private Set<Topic> topics = new HashSet<Topic>();

    private int pages;

    @Transient
    @Autowired
    Config config;


    public Forum() {
    }


    public int getId() {
        return id;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        name = name.replace("/", ",").replace("\\", ",");
        this.name = name;
    }


    public String getUrl() {
        return url;
    }


    public void setUrl(String url) {
        if (!startsWith(url, "http://")) {
            this.url = config.getBaseUrl() + url;
        } else {
            this.url = url;
        }
    }


    public Set<Topic> getTopics() {
        return topics;
    }


    public void setTopics(Set<Topic> topics) {
        this.topics = topics;
    }


    public int getPages() {
        return pages;
    }


    public void setPages(int pages) {
        this.pages = pages;
    }


    public void setConfig(Config config) {
        this.config = config;
    }


    @Override
    public String toString() {
        return "Forum \"" + getName() + "\" (" + getUrl() + ")";
    }

}
